package ru.spbau.database.group3.parser;

import ru.spbau.database.group3.queryEvaluator.Instruction;
import ru.spbau.database.group3.queryEvaluator.ErrorInstruction;
import ru.spbau.database.group3.queryEvaluator.SelectInstruction;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: stas
 * Date: 1/27/13
 * Time: 1:34 PM
 */
public class SelectCmd extends abstractCmd {
    public SelectCmd() {
        super(StringConstants.SELECT);
    }

    @Override
    public Instruction process(String cmd) throws IOException {
        try {
            List<String> col_names = getColNames(cmd);
            List<Constraint> constraints = getConstraints(cmd);
            String tableName = getTableName(cmd);
            return new SelectInstruction(tableName, constraints, col_names);
        } catch (IndexOutOfBoundsException e) {
            return new ErrorInstruction(e.getMessage());
        } catch (IllegalArgumentException e) {
            return new ErrorInstruction(e.getMessage());
        }
    }

    private List<Constraint> getConstraints(String cmd) {
        int begin = cmd.indexOf(StringConstants.WHERE);
        if(begin > 0) {
            return parseConstraintString(cmd.substring(begin + StringConstants.WHERE.length()).trim());
        }
        return new ArrayList<Constraint>();
    }

    private List<Constraint> parseConstraintString(String cmd) {
        List<Constraint> constraintList = new ArrayList<Constraint>();
        String[] constraints = cmd.split("AND");
        for(String cs : constraints) {
            constraintList.add(RecordConstraint.createConstraint(cs.trim()));
        }
        return constraintList;
    }

    private String getTableName(String cmd) {
        int begin = cmd.indexOf(StringConstants.FROM) + StringConstants.FROM.length();
        int end = cmd.indexOf(StringConstants.WHERE);
        end = end > 0 ? end : cmd.length();
        return cmd.substring(begin, end).trim();
    }

    private List<String> getColNames(String cmd) {
        int begin = StringConstants.SELECT.length();
        int end = cmd.indexOf(StringConstants.FROM);
        String[] cols = cmd.substring(begin, end).trim().split(",");
        ArrayList<String> colNames = new ArrayList<String>();
        for (String s : cols) {
            colNames.add(s.trim());
        }
        return colNames;
    }
}
